import axios from 'axios'
import ElementUI, {
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'

const createApi = {}

createApi.newRequest = (config, options) => {

// create an axios instance
  const service = axios.create({
    baseURL: localStorage.getItem('baseURL'), // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 90000 // request timeout
  })
  service.options = {
    showDefaultErrorTotal: true,
    showLoading: true,
    showLoadingText: '请稍后...'
  }
  service.loading = undefined
  if (undefined !== options) {
    service.options = options
    if (undefined !== options.showDefaultErrorTotal) {
      service.options.showDefaultErrorTotal = options.showDefaultErrorTotal
    }
    if (undefined !== options.showLoading) {
      service.options.showLoading = options.showLoading
    }
    if (undefined !== options.showLoadingText) {
      service.options.showLoadingText = options.showLoadingText
    }
  }
  if (service.options.showLoading === true) {
    service.loading = ElementUI.Loading.service({
      lock: true,
      spinner: 'el-icon-loading',
      background: 'rgba(255, 255, 255, 0.7)',
      text: service.options.showLoadingText
    })
  }

// request interceptor
  service.interceptors.request.use(
    config => {
      // do something before request is sent

      if (store.getters.token) {
        // let each request carry token
        // ['X-Token'] is a custom headers key

        // please modify it according to the actual situation
        config.headers['sessionToken'] = getToken()
      }
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

// response interceptor
  service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
      if (service.options.showLoading === true) {
        if (undefined !== service.loading) {
          service.loading.close()
        }
      }
      const res = response.data
      // console.log(res);
      if (res.code === 0) {
        // 成功
        return res
      } else if (res.code === 1) {
        if (undefined !== res['paramErrorList']) {
          if (res['paramErrorList'][0]['errorType'] === 1) {
            Message({
              message: res['paramErrorList'][0]['paramName'] + '为空' || 'Error',
              type: 'error',
              duration: 5000
            })
          } else if (res['paramErrorList'][0]['errorType'] === 2) {
            Message({
              message: res['paramErrorList'][0]['paramName'] + '错误' || 'Error',
              type: 'error',
              duration: 5000
            })
          } else {
            Message({
              message: res['paramErrorList'][0]['paramName'] || 'Error',
              type: 'error',
              duration: 5000
            })
          }
        } else {
          if (undefined === service.options.showDefaultErrorTotal || service.options.showDefaultErrorTotal === true) {
            Message({
              message: res.message || 'Error',
              type: 'error',
              duration: 5000
            })
          }
        }
        return Promise.reject(res)
      } else {
        if (undefined === service.options.showDefaultErrorTotal || service.options.showDefaultErrorTotal === true) {
          Message({
            message: res.message || 'Error',
            type: 'error',
            duration: 5000
          })
        }
        return Promise.reject(res)
      }
    },
    error => {
      if (service.options.showLoading === true) {
        if (undefined !== service.loading) {
          service.loading.close()
        }
      }
      console.error('error:' + error) // for debug
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  )
  return service(config)
}

export default createApi
